﻿using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using P2P.Client.Enums;
using P2P.Client.Model;
using P2P.Client.Tasks;
using System;
using System.Net;
using System.Text;

namespace P2P.Client.UI.Features.Server;

public partial class ServerView : UserControl
{
    private ServerViewModel _serverViewModel;

    private int _selectServerId;

    private TimerTask _timerTask;

    public ServerView()
    {
        InitializeComponent();

        var names = NameScope.GetNameScope(this);

        Button btnConnect = names.Find<Button>("BtnConnect");

        _timerTask = new TimerTask(async () => 
        {
            if (SharedModel.Instance.MainServerInfo.ConnectStatus == ConnectStatus.Connected)
            {
                await Dispatcher.UIThread.InvokeAsync(() => 
                {
                    btnConnect.Content = "断开";

                    if (_serverViewModel != null) 
                    {
                        foreach (ServerInfoViewModel item in _serverViewModel.DataGridContent)
                        {
                            if (item.Id.Value == _selectServerId)
                            {
                                item.ConnectState = "已连接";
                            }
                        }
                    }
                });
            }
            else if (SharedModel.Instance.MainServerInfo.ConnectStatus == ConnectStatus.Disconnected) 
            {
                await Dispatcher.UIThread.InvokeAsync(() =>
                {
                    btnConnect.Content = "连接";

                    if (_serverViewModel != null)
                    {
                        foreach (ServerInfoViewModel item in _serverViewModel.DataGridContent)
                        {
                            if (item.Id.Value == _selectServerId)
                            {
                                item.ConnectState = "未连接";
                            }
                        }
                    }
                });
            }
            else if (SharedModel.Instance.MainServerInfo.ConnectStatus == ConnectStatus.Connecting)
            {
                await Dispatcher.UIThread.InvokeAsync(() =>
                {
                    btnConnect.Content = "取消";

                    if (_serverViewModel != null)
                    {
                        foreach (ServerInfoViewModel item in _serverViewModel.DataGridContent)
                        {
                            if (item.Id.Value == _selectServerId)
                            {
                                _serverViewModel.SelectedServerInfo.ConnectState = "连接中";
                            }
                        }
                    }
                });
            }
        },TimeSpan.FromSeconds(10));
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void ButtonConnectToServer_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        _serverViewModel = (ServerViewModel)DataContext;

        if (!_serverViewModel.SelectedServerInfo.Id.HasValue) 
        {
            return;
        }

        Button connectToServerBtn = (Button)sender;

        if (connectToServerBtn.Content.Equals("连接"))
        {
            connectToServerBtn.Content = "取消";
            _serverViewModel.SelectedServerInfo.ConnectState = "连接中";
            _selectServerId = _serverViewModel.SelectedServerInfo.Id.Value;

            JObject data = new JObject();
            data.Add("Name", "User");
            data.Add("Method", "Login");
            data.Add("Version", "1.0");

            string req = JsonConvert.SerializeObject(R<JObject>.Ok(data));

            SharedModel.Instance.UDPSocketListener.SendTo(req,
                _serverViewModel.SelectedServerInfo.Ip, 
                _serverViewModel.SelectedServerInfo.Port.Value);

            SharedModel.Instance.MainServerInfo.ConnectStatus = ConnectStatus.Connecting;
        }
        else if (connectToServerBtn.Content.Equals("取消") || connectToServerBtn.Content.Equals("断开")) 
        {
            foreach (ServerInfoViewModel item in _serverViewModel.DataGridContent)
            {
                if (item.Id.Value == _selectServerId)
                {
                    item.ConnectState = "未连接";
                }
            }

            connectToServerBtn.Content = "连接";
            SharedModel.Instance.MainServerInfo.Clear();
        }
    } 
}